package com.sf.dlb.interceptor;

import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.service.UserInfoService;
import com.sf.dlb.config.Global;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * token检查
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    private Logger logger= LoggerFactory.getLogger(LoginHandlerInterceptor.class);
    @Resource
    private Global global;
    @Autowired
    private UserInfoService userInfoService;
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        ResultVO resultVO=userInfoService.getTokenChekout(request);
        if(resultVO.getCode()!=200){
            //请求不合法
            String responseJson= GsonUtils.getInstance().toJson(resultVO);
            returnJson(response,responseJson);
            return false;
        } else {
            //验证通过，放行；
            request.setAttribute("token",resultVO);
            return true;
        }
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }
    private void returnJson(HttpServletResponse response, String json){
        logger.info("returnJson start "+json);
        PrintWriter printWriter= null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            printWriter = response.getWriter();
            printWriter.print(json);
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("returnJson errer");
        }finally {
            if(printWriter!=null){
                printWriter.close();
            }
        }
    }
}